import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class NotepadMain extends JFrame {
    private JTabbedPane tabbedPane;
    private int tabCounter = 1;

    public NotepadMain() {
        setTitle("高级记事本");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 700);
        setLocationRelativeTo(null);

        initMenuBar();
        initTabbedPane();

        setVisible(true);
    }

    private void initMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        JMenu fileMenu = new JMenu("文件(F)");
        fileMenu.setMnemonic(KeyEvent.VK_F);

        JMenuItem newItem = new JMenuItem("新建(N)", KeyEvent.VK_N);
        newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));
        newItem.addActionListener(e -> createNewTab());

        JMenuItem openItem = new JMenuItem("打开(O)...", KeyEvent.VK_O);
        openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
        openItem.addActionListener(e -> openFile());

        JMenuItem saveItem = new JMenuItem("保存(S)", KeyEvent.VK_S);
        saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
        saveItem.addActionListener(e -> saveFile());

        JMenuItem exitItem = new JMenuItem("退出(X)", KeyEvent.VK_X);
        exitItem.addActionListener(e -> System.exit(0));

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);

        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
    }

    private void initTabbedPane() {
        tabbedPane = new JTabbedPane();
        // 设置标签页可关闭
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        tabbedPane.putClientProperty("JTabbedPane.tabClosable", true);
        tabbedPane.putClientProperty("JTabbedPane.tabCloseCallback", (Runnable) () -> {
            tabbedPane.remove(tabbedPane.getSelectedIndex());
        });
        
        // 添加标签页关闭监听器
        tabbedPane.addChangeListener(e -> {
            // 确保至少有一个标签页存在
            if (tabbedPane.getTabCount() == 0) {
                createNewTab();
            }
        });
        
        createNewTab();
        add(tabbedPane, BorderLayout.CENTER);
    }

    private void createNewTab() {
        // 使用支持语法高亮的文本区域
        SyntaxHighlighterTextArea textArea = new SyntaxHighlighterTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        
        // 创建增强的行头面板，包含行号和代码折叠功能
        EnhancedRowHeaderPanel rowHeaderPanel = new EnhancedRowHeaderPanel(textArea);
        scrollPane.setRowHeaderView(rowHeaderPanel);
        
        String title = "未命名" + tabCounter++;
        tabbedPane.addTab(title, scrollPane);
        tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
        
        // 添加关闭按钮到标签页
        int index = tabbedPane.getTabCount() - 1;
        JButton closeButton = new JButton("×");
        closeButton.setPreferredSize(new Dimension(16, 16));
        closeButton.setFont(new Font("Arial", Font.BOLD, 10));
        closeButton.setToolTipText("关闭标签页");
        closeButton.setOpaque(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setBorderPainted(false);
        closeButton.setFocusable(false);
        closeButton.addActionListener(e -> {
            if (tabbedPane.getTabCount() > 1) {
                tabbedPane.remove(index);
            } else {
                // 如果是最后一个标签页，则创建一个新的空标签页
                createNewTab();
                tabbedPane.remove(index);
            }
        });
        
        tabbedPane.setTabComponentAt(index, new TabPanel(title, closeButton));
    }
    
    // 标签页面板类，包含标题和关闭按钮
    private class TabPanel extends JPanel {
        public TabPanel(String title, JButton closeButton) {
            setOpaque(false);
            JLabel label = new JLabel(title);
            add(label);
            add(closeButton);
        }
    }
    
    private void createNewTabWithContent(String content, String fileName) {
        // 使用支持语法高亮的文本区域
        SyntaxHighlighterTextArea textArea = new SyntaxHighlighterTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        
        // 对于大文件，暂时禁用语法高亮以提高加载速度
        if (content.length() > 50000) { // 如果文件大于50KB
            textArea.setHighlightingEnabled(false);
        }
        
        textArea.setText(content);
        
        // 重新启用语法高亮
        if (content.length() > 50000) {
            SwingUtilities.invokeLater(() -> {
                textArea.setHighlightingEnabled(true);
                textArea.repaint();
            });
        }
        
        // 创建增强的行头面板，包含行号和代码折叠功能
        EnhancedRowHeaderPanel rowHeaderPanel = new EnhancedRowHeaderPanel(textArea);
        scrollPane.setRowHeaderView(rowHeaderPanel);
        
        tabbedPane.addTab(fileName, scrollPane);
        tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
        
        // 添加关闭按钮到标签页
        int index = tabbedPane.getTabCount() - 1;
        JButton closeButton = new JButton("×");
        closeButton.setPreferredSize(new Dimension(16, 16));
        closeButton.setFont(new Font("Arial", Font.BOLD, 10));
        closeButton.setToolTipText("关闭标签页");
        closeButton.setOpaque(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setBorderPainted(false);
        closeButton.setFocusable(false);
        closeButton.addActionListener(e -> tabbedPane.remove(index));
        
        tabbedPane.setTabComponentAt(index, new TabPanel(fileName, closeButton));
    }

    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line).append("\n");
                }
                
                // 创建带内容的新标签页
                createNewTabWithContent(content.toString(), selectedFile.getName());
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "打开文件时出错: " + e.getMessage(), 
                                            "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void saveFile() {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showSaveDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            // 这里应该添加保存文件的逻辑
            JOptionPane.showMessageDialog(this, "文件已保存");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(NotepadMain::new);
    }
}